﻿using Ebusiness_Authservice.Entities;
using Ebusiness_Authservice.Services.Dtos;
using Ebusiness_OrderService.Repositorys;
using Nacos;
using Ocelot.RequestId;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;

namespace Ebusiness_Authservice.Services
{
    [Dependency(ServiceLifetime.Singleton)]
    [RemoteService(false)]
    public class ApplicationUserService : CrudAppService<ApplicationUser, ApplicationUserDto, Guid>, IApplicationUserService
    {
        public IAuthserRepository AuthserRepository;

        public ApplicationUserService(IAuthserRepository repository) : base(repository)
        {
            AuthserRepository = repository;
        }

        public async override Task<ApplicationUserDto> CreateAsync(ApplicationUserDto input)
        {
            string msg = "";
            ApplicationUserDto applicationUserDto = null;
            // 检查用户名是否已存在
            if (await AuthserRepository.FirstOrDefaultAsync(u => u.UserName == input.UserName) != null)
            {
                msg = "Username:用户名已存在";
                return applicationUserDto;
            }

            // 检查邮箱是否已存在
            if (await AuthserRepository.FirstOrDefaultAsync(u => u.Email == input.Email) != null)
            {
                msg = "Email:邮箱地址已被注册";
                return applicationUserDto;
            }
            ApplicationUser applicationUser = ObjectMapper.Map<ApplicationUserDto, ApplicationUser>(input);
            // 创建新用户对象
            applicationUser.PasswordHash = BCrypt.Net.BCrypt.HashPassword(input.Password); // 使用BCrypt加密密码
            //var user = new ApplicationUser
            //{
            //    UserName = input.UserName,                                    // 设置用户名
            //    Email = input.Email,                                          // 设置邮箱
            //    PasswordHash = BCrypt.Net.BCrypt.HashPassword(input.Password), // 使用BCrypt加密密码
            //    Roles = new List<string> { "User" }                            // 设置默认角色为User
            //};
            ApplicationUser user = await AuthserRepository.InsertAsync(applicationUser);
            ApplicationUserDto dto = ObjectMapper.Map<ApplicationUser, ApplicationUserDto>(user);
            return dto;
        }
    }
}
